<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>

<body>
  <canvas width="600" height="400"></canvas>
  <script>
    let canvas = document.querySelector("canvas")
    let ctx = canvas.getContext("2d")


    ctx.fillStyle = "red"
    let x = 0, y = 0;
    let xTag = true, yTag = true;    //true:正方向移动   false:负方向移动

    setInterval(() => {
      ctx.clearRect(x, y, 50, 50)

      if (xTag && x > 550) {
        xTag = false
      } else if(xTag==false && x<0){
        xTag = true;
      }

      if (xTag) {
        x++
      } else {
        x--
      }


      if (yTag==true && y>=350) {
        yTag = false
      } else if(yTag==false && y<=0) {
        yTag = true;
      }

      if (yTag) {
        y++
      } else {
        y--
      }
      ctx.fillRect(x, y, 50, 50)
    }, 10)


  </script>
</body>